#include "contactuserlist.h"
#include<QRandomGenerator>
#include<QWheelEvent>
#include<QScrollBar>
#include <QTimer>
#include <QCoreApplication>
#include"listitembase.h"
#include"tcpmgr.h"
#include"usermgr.h"
ContactUserList::ContactUserList(QWidget *parent):_load_pending(false)
{
    Q_UNUSED(parent);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    //安装事件过滤器
    this->viewport()->installEventFilter(this);

    //从数据库传输过来的的数据进行列表加载
    addContactUserList();
    //设置点击的信号和槽
    connect(this,&QListWidget::itemClicked,this,&ContactUserList::slot_item_clicked);

    //链接对端的同意认证后通知的信号
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_add_auth_friend,
            this,&ContactUserList::slot_add_auth_friend);
    //链接自己点击同意认证后界面刷新
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_auth_rsp,
            this,&ContactUserList::slot_auth_rsp);
}

void ContactUserList::ShowRedPoint(bool bshow)
{
    _add_friend_item->ShowRedPoint(bshow);
}

bool ContactUserList::eventFilter(QObject *object, QEvent *event)
{
    //检查鼠标是否进入
    if(object==this->viewport()){
        if(event->type()==QEvent::Enter){
            this->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        }
        else if(event->type()==QEvent::Leave){
            this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        }
    }
    //检查鼠标是否是滚轮事件
    if(object==this->viewport()&&event->type()==QEvent::Wheel){
        QWheelEvent*wheelEvent=static_cast<QWheelEvent*>(event);
        int numDegrees=wheelEvent->angleDelta().y()/8;
        int numSteps=numDegrees/15;

        this->verticalScrollBar()->setValue(this->verticalScrollBar()->value()-numSteps);

        QScrollBar* scrollBar=this->verticalScrollBar();
        int maxScrollValue=scrollBar->maximum();
        int currentValue=scrollBar->value();

        if(maxScrollValue-currentValue<=0){
            auto b_loaded=UserMgr::GetInstance()->IsLoadConFin();
            //检测是否还有数据
            if(b_loaded){
                qDebug()<<"The Contact has finished ";
                return true;
            }
            if(_load_pending){
                return true;
            }
            _load_pending=true;
            QTimer::singleShot(100, [this](){
                _load_pending = false;
            });
            qDebug()<<"load more contact user";
            emit sig_loading_contact_user();
        }
        return true;
    }
    return QListWidget::eventFilter(object,event);
}

void ContactUserList::addContactUserList()
{
    auto* groupTip=new GroupTipItem();
    groupTip->SetGroupTip(tr("新的朋友"));
    QListWidgetItem*item=new QListWidgetItem;
    item->setSizeHint(groupTip->sizeHint());
    this->addItem(item);
    this->setItemWidget(item,groupTip);
    item->setFlags(item->flags()&~Qt::ItemIsSelectable);

    _add_friend_item=new ConUserItem();
    _add_friend_item->setObjectName("new_friend_item");
    _add_friend_item->SetInfo(0,tr("新的朋友"),":/images/add_tip.png");
    _add_friend_item->SetItemType(ListItemType::APPLY_FRIEND_ITEM);

    QListWidgetItem* add_item=new QListWidgetItem;
    add_item->setSizeHint(_add_friend_item->sizeHint());
    this->addItem(add_item);
    this->setItemWidget(add_item,_add_friend_item);

    this->setCurrentItem(add_item);

    auto* groupCon=new GroupTipItem();
    groupCon->SetGroupTip(tr("联系人"));
    _groupitem=new QListWidgetItem;
    _groupitem->setSizeHint(groupCon->sizeHint());
    this->addItem(_groupitem);
    this->setItemWidget(_groupitem,groupCon);
    _groupitem->setFlags(_groupitem->flags()&~Qt::ItemIsSelectable);

    //加载后端传过来的好友列表
    auto con_list = UserMgr::GetInstance()->GetConListPerPage();
    for(auto & con_ele : con_list){
        auto *con_user_wid = new ConUserItem();
        con_user_wid->SetInfo(con_ele->_uid,con_ele->_name, con_ele->_icon);
        QListWidgetItem *item = new QListWidgetItem;
        item->setSizeHint(con_user_wid->sizeHint());
        this->addItem(item);
        this->setItemWidget(item, con_user_wid);
    }

    UserMgr::GetInstance()->UpdateContactLoadedCount();

    //模拟数据
    for(int i=0;i<13;i++){
        int randomValue=QRandomGenerator::global()->bounded(100);
        int str_i=randomValue%strs.size();
        int head_i=randomValue%heads.size();
        int name_i=randomValue%names.size();

        auto* con_user_wid=new ConUserItem();
        con_user_wid->SetInfo(0,names[name_i],heads[head_i]);
        QListWidgetItem* item2=new QListWidgetItem;

        item2->setSizeHint(con_user_wid->sizeHint());
        this->addItem(item2);
        this->setItemWidget(item2,con_user_wid);
    }
}

void ContactUserList::slot_item_clicked(QListWidgetItem *item)
{
    QWidget* widget=this->itemWidget(item);
    if(!widget){
        qDebug()<<"slot item clicked widget is nullptr";
        return;
    }
    ListItemBase* customItem=qobject_cast<ListItemBase*>(widget);
    if(!customItem){
        qDebug()<< "slot item clicked widget is nullptr";
        return;
    }
    auto itemType=customItem->GetItemType();
    if(itemType==ListItemType::INVALID_ITEM||itemType==ListItemType::GROUP_TIP_ITEM){
        qDebug()<<"slot invalid item clicked";
        return;
    }
    if(itemType==ListItemType::APPLY_FRIEND_ITEM){
        qDebug()<<"apply friend item clicked";
        emit sig_switch_apply_friend_page();
        return;
    }
    if(itemType==ListItemType::CONTACT_USER_ITEM){
        qDebug()<<"contact user item clicked";
        auto con_item=qobject_cast<ConUserItem*>(customItem);
        auto user_info=con_item->GetInfo();
        emit sig_switch_friend_info_page(user_info);
        return;
    }
}

void ContactUserList::slot_add_auth_friend(std::shared_ptr<AuthInfo>auth_info)
{
    qDebug()<<"slot add auth friend";
    //防止重复添加相同好友
    bool isFriend=UserMgr::GetInstance()->CheckFriendById(auth_info->_uid);
    if(isFriend){
        return;
    }
    //在groupitem之后插入新项
    auto* con_user_wid=new ConUserItem();
    con_user_wid->SetInfo(auth_info);
    QListWidgetItem* item=new QListWidgetItem;
    item->setSizeHint(con_user_wid->sizeHint());

    //获取groupitem索引
    int index=this->row(_groupitem);
    this->insertItem(index+1,item);
    this->setItemWidget(item,con_user_wid);
}

void ContactUserList::slot_auth_rsp(std::shared_ptr<AuthRsp>auth_rsp)
{
    qDebug()<<"slot auth rsp called";
    bool isFriend=UserMgr::GetInstance()->CheckFriendById(auth_rsp->_uid);
    if(isFriend){
        return;
    }

    // 在 groupitem 之后插入新项
    int randomValue = QRandomGenerator::global()->bounded(100); // 生成0到99之间的随机整数
    int head_i = randomValue%heads.size();

    auto* con_user_wid=new ConUserItem();
    con_user_wid->SetInfo(auth_rsp->_uid,auth_rsp->_name,heads[head_i]);
    QListWidgetItem* item=new QListWidgetItem;
    item->setSizeHint(con_user_wid->sizeHint());


    // 获取 groupitem 的索引
    int index = this->row(_groupitem);
    // 在 groupitem 之后插入新项
    this->insertItem(index + 1, item);

    this->setItemWidget(item, con_user_wid);

}
